/*
 * Copyright (c) 2020
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-08-13     chao         first version
 */

#include <board.h>

#ifdef BSP_USING_LCD
#include <lcd_port.h>
#include <string.h>

#define DRV_DEBUG
#define LOG_TAG             "drv.lcd"
#include <drv_log.h>

#define Bank1_SRAM4_ADDR        ((uint32_t)0x6C000000)
#define LCD_COMMAND_ADDRESS     ((uint32_t)0x6C000000)
#define LCD_PARAMETER_ADDRESS   ((uint32_t)0x6C000800)//A10


#define LCD_DEVICE(dev)     (struct drv_lcd_device*)(dev)

void lcd_reflesh(uint16_t *pFrameBuffer);

struct drv_lcd_device
{
    struct rt_device parent;

    struct rt_device_graphic_info lcd_info;

    struct rt_semaphore lcd_lock;

    /* 0:front_buf is being used 1: back_buf is being used*/
//    rt_uint8_t cur_buf;
//    rt_uint8_t *front_buf;
//    rt_uint8_t *back_buf;
};

struct drv_lcd_device _lcd;

static rt_err_t drv_lcd_init(struct rt_device *device)
{
    struct drv_lcd_device *lcd = LCD_DEVICE(device);
    /* nothing, right now */
    lcd = lcd;
    return RT_EOK;
}

static rt_err_t drv_lcd_control(struct rt_device *device, int cmd, void *args)
{
    struct drv_lcd_device *lcd = LCD_DEVICE(device);
    uint16_t *pFrameBuffer = NULL;

    switch (cmd)
    {
    case RTGRAPHIC_CTRL_RECT_UPDATE:
    {
#if 0
        /* update */
        if (_lcd.cur_buf)
        {
            /* back_buf is being used */
            memcpy(_lcd.front_buf, _lcd.lcd_info.framebuffer, LCD_FRAMEBUFFER_SIZE);
            /* Configure the color frame buffer start address */
            pFrameBuffer = (uint16_t *)_lcd.front_buf;
            _lcd.cur_buf = 0;
        }
        else
        {
            /* front_buf is being used */
            memcpy(_lcd.back_buf, _lcd.lcd_info.framebuffer, LCD_FRAMEBUFFER_SIZE);
            /* Configure the color frame buffer start address */
            pFrameBuffer = (uint16_t *)_lcd.back_buf;
            _lcd.cur_buf = 1;
        }
#endif
        pFrameBuffer = (uint16_t *)_lcd.lcd_info.framebuffer;
        rt_sem_take(&_lcd.lcd_lock, RT_TICK_PER_SECOND / 20);
        lcd_reflesh(pFrameBuffer);
        rt_sem_release(&_lcd.lcd_lock);
    }
    break;

    case RTGRAPHIC_CTRL_GET_INFO:
    {
        struct rt_device_graphic_info *info = (struct rt_device_graphic_info *)args;

        RT_ASSERT(info != RT_NULL);
        info->pixel_format  = lcd->lcd_info.pixel_format;
        info->bits_per_pixel = 16;
        info->width         = lcd->lcd_info.width;
        info->height        = lcd->lcd_info.height;
        info->framebuffer   = lcd->lcd_info.framebuffer;
    }
    break;
    }

    return RT_EOK;
}

void lcd_write_cmd(uint16_t Command)
{
    *((uint16_t *)(LCD_COMMAND_ADDRESS)) = Command;
}

void lcd_write_param(uint16_t Parameter)
{
    *((uint16_t *)(LCD_PARAMETER_ADDRESS)) = Parameter;
}

uint16_t lcd_read_param(void)
{
    uint16_t data=0;
    
    data = *((volatile uint16_t *)(LCD_PARAMETER_ADDRESS));
    return data;
}

static int lcd_config(void)
{
    __IO uint32_t tmpmrd = 0;
    
    /* Insert 100 ms delay */
    /* interrupt is not enable, just to delay some time. */
    for (tmpmrd = 0; tmpmrd < 0xff; tmpmrd ++);
    lcd_write_cmd(CMD_SleepOUT);   // Sleep out
    /* Insert 100 ms delay */
    /* interrupt is not enable, just to delay some time. */
    for (tmpmrd = 0; tmpmrd < 0xff; tmpmrd ++);
    lcd_write_cmd(CMD_DisplayON);   // Display on

    lcd_write_cmd(CMD_PowercontrolB);  
    lcd_write_param((uint16_t)0x00);
    lcd_write_param((uint16_t)0x83);
    lcd_write_param((uint16_t)0X30);
    lcd_write_cmd(CMD_PowerOnSequenceControl);  
    lcd_write_param((uint16_t)0x64);
    lcd_write_param((uint16_t)0x03);
    lcd_write_param((uint16_t)0X12);
    lcd_write_param((uint16_t)0X81);
    lcd_write_cmd(CMD_DriverTimingControlA); 
    lcd_write_param((uint16_t)0x85);
    lcd_write_param((uint16_t)0x01);
    lcd_write_param((uint16_t)0x79);
    lcd_write_cmd(CMD_PowercontrolA);  
    lcd_write_param((uint16_t)0x39);
    lcd_write_param((uint16_t)0x2C);
    lcd_write_param((uint16_t)0x00);
    lcd_write_param((uint16_t)0x34);
    lcd_write_param((uint16_t)0x02);
    lcd_write_cmd(CMD_PumpRatioControl);   
    lcd_write_param((uint16_t)0x20);
    lcd_write_cmd(CMD_DriverTimingControlB);  
    lcd_write_param((uint16_t)0x00);
    lcd_write_param((uint16_t)0x00);
    lcd_write_cmd(CMD_PowerControl1);  
    lcd_write_param((uint16_t)0x1D); 
    lcd_write_cmd(CMD_PowerControl2);  
    lcd_write_param((uint16_t)0x11); 
    lcd_write_cmd(CMD_VCOMControl1);  
    lcd_write_param((uint16_t)0x33);
    lcd_write_param((uint16_t)0x34);
    lcd_write_cmd(CMD_VCOMControl2);  
    lcd_write_param((uint16_t)0Xbe);
    lcd_write_cmd(CMD_MemoryAccessControl);   
    lcd_write_param(MX_MY_MV_BGR(0, 1, 0, 1));/* scan mode */
    lcd_write_cmd(CMD_FrameControlInNormalMode);  
    lcd_write_param((uint16_t)0x00);
    lcd_write_param((uint16_t)0x1B);
    lcd_write_cmd(CMD_DisplayFunctionControl);  
    lcd_write_param((uint16_t)0x0A);
    lcd_write_param((uint16_t)0xA2);
    lcd_write_cmd(CMD_Enable3G);  
    lcd_write_param((uint16_t)0x00);
    lcd_write_cmd(CMD_GammaSet);  
    lcd_write_param((uint16_t)0x01);
    lcd_write_cmd(CMD_PositiveGammaCorrection);  
    lcd_write_param((uint16_t)0x0F);
    lcd_write_param((uint16_t)0x23);
    lcd_write_param((uint16_t)0x1F);
    lcd_write_param((uint16_t)0x09);
    lcd_write_param((uint16_t)0x0f);
    lcd_write_param((uint16_t)0x08);
    lcd_write_param((uint16_t)0x4B);
    lcd_write_param((uint16_t)0Xf2);
    lcd_write_param((uint16_t)0x38);
    lcd_write_param((uint16_t)0x09);
    lcd_write_param((uint16_t)0x13);
    lcd_write_param((uint16_t)0x03);
    lcd_write_param((uint16_t)0x12);
    lcd_write_param((uint16_t)0x07);
    lcd_write_param((uint16_t)0x04);
    lcd_write_cmd(CMD_NegativeGammaCorrection);  
    lcd_write_param((uint16_t)0x00);
    lcd_write_param((uint16_t)0x1d);
    lcd_write_param((uint16_t)0x20);
    lcd_write_param((uint16_t)0x02);
    lcd_write_param((uint16_t)0x11);
    lcd_write_param((uint16_t)0x07);
    lcd_write_param((uint16_t)0x34);
    lcd_write_param((uint16_t)0x81);
    lcd_write_param((uint16_t)0x46);
    lcd_write_param((uint16_t)0x06);
    lcd_write_param((uint16_t)0x0e);
    lcd_write_param((uint16_t)0x0c);
    lcd_write_param((uint16_t)0x32);
    lcd_write_param((uint16_t)0x38);
    lcd_write_param((uint16_t)0x0F);
    
    lcd_write_cmd(CMD_DisplayInversionON);  

    //user add 
    lcd_write_cmd(CMD_PixelFormatSet);   //COLMOD: Pixel Format Set
    lcd_write_param((uint16_t)0x55);
//    LCD_BL_ON;

    lcd_reflesh((uint16_t *)(_lcd.lcd_info.framebuffer));
    LOG_D("lcd config success.");

    return 0;
}

rt_err_t stm32_lcd_init(struct drv_lcd_device *lcd)
{
    SRAM_HandleTypeDef hsram1;
    FSMC_NORSRAM_TimingTypeDef Timing = {0};

    /** Perform the SRAM1 memory initialization sequence
    */
    hsram1.Instance = FSMC_NORSRAM_DEVICE;
    hsram1.Extended = FSMC_NORSRAM_EXTENDED_DEVICE;
    hsram1.State    = HAL_SRAM_STATE_RESET;
    /* hsram1.Init */
    hsram1.Init.NSBank = FSMC_NORSRAM_BANK4;
    hsram1.Init.DataAddressMux = FSMC_DATA_ADDRESS_MUX_DISABLE;
    hsram1.Init.MemoryType = FSMC_MEMORY_TYPE_SRAM;
    hsram1.Init.MemoryDataWidth = FSMC_NORSRAM_MEM_BUS_WIDTH_16;
    hsram1.Init.BurstAccessMode = FSMC_BURST_ACCESS_MODE_DISABLE;
    hsram1.Init.WaitSignalPolarity = FSMC_WAIT_SIGNAL_POLARITY_LOW;
    hsram1.Init.WrapMode = FSMC_WRAP_MODE_DISABLE;
    hsram1.Init.WaitSignalActive = FSMC_WAIT_TIMING_BEFORE_WS;
    hsram1.Init.WriteOperation = FSMC_WRITE_OPERATION_ENABLE;
    hsram1.Init.WaitSignal = FSMC_WAIT_SIGNAL_DISABLE;
    hsram1.Init.ExtendedMode = FSMC_EXTENDED_MODE_DISABLE;
    hsram1.Init.AsynchronousWait = FSMC_ASYNCHRONOUS_WAIT_DISABLE;
    hsram1.Init.WriteBurst = FSMC_WRITE_BURST_DISABLE;
    /* Timing */
    Timing.AddressSetupTime = 0;
    Timing.AddressHoldTime = 0;
    Timing.DataSetupTime = 1;
    Timing.BusTurnAroundDuration = 0;
    Timing.CLKDivision = 0;
    Timing.DataLatency = 0;
    Timing.AccessMode = FSMC_ACCESS_MODE_A;
    /* ExtTiming */

    if (HAL_SRAM_Init(&hsram1, &Timing, NULL) != HAL_OK)
    {
        LOG_E("lcd fsmc init failed!");
        return -RT_ERROR;
    }
    else
    {
        LOG_D("lcd fsmc init success");
    }

    /** Disconnect NADV
    */

    __HAL_AFIO_FSMCNADV_DISCONNECTED();

    return RT_EOK;
}

/**
  * @brief  
  * @param  
  * @retval 
  */
void lcd_set_window(uint16_t sx, uint16_t sy, uint16_t ex, uint16_t ey)
{
    lcd_write_cmd(CMD_ColumnAddressSet);
    lcd_write_param((uint16_t)((sx&0xFF00)>>8));
    lcd_write_param((uint16_t)((sx&0x00FF)>>0));
    lcd_write_param((uint16_t)((ex&0xFF00)>>8));
    lcd_write_param((uint16_t)((ex&0x00FF)>>0));
    lcd_write_cmd(CMD_PageAddressSet);
    lcd_write_param((uint16_t)((sy&0xFF00)>>8));
    lcd_write_param((uint16_t)((sy&0x00FF)>>0));
    lcd_write_param((uint16_t)((ey&0xFF00)>>8));
    lcd_write_param((uint16_t)((ey&0x00FF)>>0));
}

/**
  * @brief  lcd clear the screen
  * @param  Color. 
  *   This parameter can be one of the following values:
  *     @arg COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_WHITE, COLOR_BLACK and so on.
  * @retval  none.
  */
void lcd_reflesh(uint16_t *pFrameBuffer)
{
    uint32_t pixel=LCD_WIDTH * LCD_HEIGHT;
    
    lcd_set_window(0, 0, LCD_WIDTH-1, LCD_HEIGHT-1);
    lcd_write_cmd(CMD_MemoryWrite);
//#if (LCD_DRIVE_BY_FSMC && TRANSFER_BY_DMA)
//    vDma1Ch1M2M((uint32_t)&xLcd.background_color, LCD_PARAMETER_ADDRESS, pixel, 0);
//#else
    while (pixel--) lcd_write_param(*pFrameBuffer);
//#endif
}


#if defined(LCD_BACKLIGHT_USING_PWM)
void turn_on_lcd_backlight(void)
{
    struct rt_device_pwm *pwm_dev;

    /* turn on the LCD backlight */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(LCD_PWM_DEV_NAME);
    /* pwm frequency:100K = 10000ns */
    rt_pwm_set(pwm_dev, LCD_PWM_DEV_CHANNEL, 10000, 10000);
    rt_pwm_enable(pwm_dev, LCD_PWM_DEV_CHANNEL);
}
#elif defined(LCD_BACKLIGHT_USING_GPIO)
void turn_on_lcd_backlight(void)
{
    rt_pin_mode(LCD_BL_GPIO_NUM, PIN_MODE_OUTPUT);
    rt_pin_write(LCD_BL_GPIO_NUM, PIN_HIGH);
}
#else
void turn_on_lcd_backlight(void)
{
    
}
#endif

uint32_t lcd_framebuffer_addr(void)
{
    return (uint32_t)_lcd.lcd_info.framebuffer;
}

#ifdef RT_USING_DEVICE_OPS
const static struct rt_device_ops lcd_ops =
{
    drv_lcd_init,
    RT_NULL,
    RT_NULL,
    RT_NULL,
    RT_NULL,
    drv_lcd_control
};
#endif

int drv_lcd_hw_init(void)
{
    rt_err_t result = RT_EOK;
    struct rt_device *device = &_lcd.parent;

    /* memset _lcd to zero */
    memset(&_lcd, 0x00, sizeof(_lcd));

    /* init lcd_lock semaphore */
    result = rt_sem_init(&_lcd.lcd_lock, "lcd_lock", 0, RT_IPC_FLAG_FIFO);
    if (result != RT_EOK)
    {
        LOG_E("init semaphore failed!\n");
        result = -RT_ENOMEM;
        goto __exit;
    }

    /* config LCD dev info */
    _lcd.lcd_info.height = LCD_HEIGHT;
    _lcd.lcd_info.width = LCD_WIDTH;
    _lcd.lcd_info.bits_per_pixel = LCD_BITS_PER_PIXEL;
    _lcd.lcd_info.pixel_format = LCD_PIXEL_FORMAT;
#if 1
    /* malloc memory for Triple Buffering */
    _lcd.lcd_info.framebuffer = rt_malloc(sizeof(uint16_t));
//    _lcd.lcd_info.framebuffer = rt_malloc(LCD_FRAMEBUFFER_SIZE);
//    _lcd.back_buf = rt_malloc(LCD_FRAMEBUFFER_SIZE);
//    _lcd.front_buf = rt_malloc(LCD_FRAMEBUFFER_SIZE);
    if (_lcd.lcd_info.framebuffer == RT_NULL/* || _lcd.back_buf == RT_NULL || _lcd.front_buf == RT_NULL*/)
    {
        LOG_E("init frame buffer failed!\n");
        result = -RT_ENOMEM;
        goto __exit;
    }

    /* memset buff to 0xFF */
    memset(_lcd.lcd_info.framebuffer, 0, sizeof(uint16_t));
//    memset(_lcd.lcd_info.framebuffer, 0, LCD_FRAMEBUFFER_SIZE);
//    memset(_lcd.back_buf, 0, LCD_FRAMEBUFFER_SIZE);
//    memset(_lcd.front_buf, 0, LCD_FRAMEBUFFER_SIZE);
#endif
    device->type    = RT_Device_Class_Graphic;
#ifdef RT_USING_DEVICE_OPS
    device->ops     = &lcd_ops;
#else
    device->init    = drv_lcd_init;
    device->control = drv_lcd_control;
#endif

    /* register lcd device */
    rt_device_register(device, "lcd", RT_DEVICE_FLAG_RDWR);

    /* init stm32 LTDC */
    rt_sem_take(&_lcd.lcd_lock, RT_TICK_PER_SECOND / 20);
    if (stm32_lcd_init(&_lcd) != RT_EOK)
    {
        result = -RT_ERROR;
        goto __exit;
    }
    else
    {
        lcd_config();
        turn_on_lcd_backlight();
    }
    rt_sem_release(&_lcd.lcd_lock);

__exit:
    if (result != RT_EOK)
    {
        rt_sem_delete(&_lcd.lcd_lock);
#if 0
        if (_lcd.lcd_info.framebuffer)
        {
            rt_free(_lcd.lcd_info.framebuffer);
        }
        if (_lcd.back_buf)
        {
            rt_free(_lcd.back_buf);
        }

        if (_lcd.front_buf)
        {
            rt_free(_lcd.front_buf);
        }
#endif
    }
    return result;
}
INIT_DEVICE_EXPORT(drv_lcd_hw_init);

#ifdef DRV_DEBUG
#ifdef FINSH_USING_MSH
int lcd_test()
{
    struct drv_lcd_device *lcd;
    lcd = (struct drv_lcd_device *)rt_device_find("lcd");
    uint8_t count = 3;

    while (count--)
    {
        /* red */
        for (int i = 0; i < /*LCD_FRAMEBUFFER_SIZE*/sizeof(uint16_t) / 2; i++)
        {
            lcd->lcd_info.framebuffer[2 * i] = 0x00;
            lcd->lcd_info.framebuffer[2 * i + 1] = 0xF8;
        }
        lcd->parent.control(&lcd->parent, RTGRAPHIC_CTRL_RECT_UPDATE, RT_NULL);
        rt_thread_mdelay(1000);
        /* green */
        for (int i = 0; i < /*LCD_FRAMEBUFFER_SIZE*/sizeof(uint16_t) / 2; i++)
        {
            lcd->lcd_info.framebuffer[2 * i] = 0xE0;
            lcd->lcd_info.framebuffer[2 * i + 1] = 0x07;
        }
        lcd->parent.control(&lcd->parent, RTGRAPHIC_CTRL_RECT_UPDATE, RT_NULL);
        rt_thread_mdelay(1000);
        /* blue */
        for (int i = 0; i < /*LCD_FRAMEBUFFER_SIZE*/sizeof(uint16_t) / 2; i++)
        {
            lcd->lcd_info.framebuffer[2 * i] = 0x1F;
            lcd->lcd_info.framebuffer[2 * i + 1] = 0x00;
        }
        lcd->parent.control(&lcd->parent, RTGRAPHIC_CTRL_RECT_UPDATE, RT_NULL);
        rt_thread_mdelay(1000);
    }
    return RT_EOK;
}
MSH_CMD_EXPORT(lcd_test, lcd_test);
#endif /* FINSH_USING_MSH */
#endif /* DRV_DEBUG */
#endif /* BSP_USING_LCD */


